import { defineStore } from "pinia";
import {
  customerAttendeeAPI,
  customerVisitRecordAPI,
  getCompanyBaseInfo,
  getCompetitorsDetailAPI,
  getCustomerCompetitorsAPI,
  getCustomerRiskAPI,
  getCustomerTodoListAPI,
  myCustomerAPI,
  getCustomerMeddicAPI,
  remakeCustomerMeddicAPI,
  updateCustomerMeddicAPI,
  updateCustomerTodoStatusAPI
} from "@/services/customer";


import { getOuterFiledPartnerAPI } from "@/services/orderVisit";

import { getCommunicationStagesAPI } from "@/services/myXmate";

import dayjs from "dayjs";
import { getDateRange, formatCompletionTime, ParameterDateType, getLongTimeAgo } from "@/utils/timeTool";

export const useCustomerStore = defineStore("customerStore", {
  state: () => ({
    filterStartTime: "",
    filterEndTime: "",
    customerList: [],
    outerFiledTemple: [],
    companyName: "",
    companyId: "",
    companyInfo: {},
    myTeam: false,
    dptIds: "",

    currentCompanyId: "",
    currentCustomerId: "",
    currentCompanyInfo: {
      baseInfo: null,
      recruitmentInfo: null,
      branches: null,
      industry: null
    },

    visitRecordList: [], // 我的沟通列表
    customerAttendeeList: [], // 客户参会人列表
    riskInfo: {}, // 风险信息
    toDoList: [], // 待办列表
    competitorsList: [], // 竞争对手列表
    competitorsInfo: {},

    systemTags: [],

    customerStartTime: "",
    customerEndTime: "",
    customerTimer: null,

    communicationStages: [], // 沟通环节列表

    meddicInfo: [] // 客户MEDDIC
  }),

  getters: {
    getDefaultDateUnit() {
      const month = "month";
      const quarter = "quarter";
      const year = "year";
      const none = "none";
      if (!this.filterStartTime || this.filterStartTime.length === 0) {
        return quarter;
      }
      const monthStartDate = getDateRange(month).startDate;
      const quarterStartDate = getDateRange(quarter).startDate;
      const yearStartDate = getDateRange(year).startDate;
      if (monthStartDate === this.filterStartTime) return month;
      if (quarterStartDate === this.filterStartTime) return quarter;
      if (yearStartDate === this.filterStartTime) return year;
      return none;
    }
  },

  actions: {
    setCurrentCompanyId(id) {
      this.currentCompanyId = id;
    },

    setCurrentCompanyName(name) {
      this.companyName = name;
    },

    async getCommunicationStagesAction() {
      const data = await getCommunicationStagesAPI({ type: 0, targetId: "" });
      const { datas } = data;
      this.communicationStages = datas;
    },

    setCurrentCustomerId(id) {
      this.currentCustomerId = id;
    },

    setStartTime(startTime) {
      console.log("setStartTime: ", startTime);
      this.filterStartTime = startTime;
    },

    setEndTime(endTime) {
      this.filterEndTime = endTime;
    },

    setMyteam(v) {
      if (v === "true") {
        this.myTeam = true;
        return;
      }
      if (v === "false") {
        this.myTeam = false;
        return;
      }
      this.myTeam = v;
    },
    setDptIds(v) {
      this.dptIds = v;
    },

    async getCompanyBaseInfoAction() {
      if (!this.currentCompanyId) {
        return;
      }
      this.currentCompanyInfo.baseInfo = await getCompanyBaseInfo(
        this.currentCompanyId
      );
    },

    async getCustomerListAction() {
      const data = await myCustomerAPI();
      this.customerList = data.datas;
    },

    async getVisitRecordList(
      startTime,
      endTime = dayjs().format("YYYY-MM-DD")
    ) {
      const parameter = {
        searchKey: "",
        startTime: formatCompletionTime(startTime, ParameterDateType.START_DATE),
        endTime: formatCompletionTime(endTime, ParameterDateType.ENE_DATE),
        pageSize: 600,
        myTeam: this.myTeam,
      };
      const data = await customerVisitRecordAPI(
        this.currentCustomerId,
        parameter
      );
      this.visitRecordList = data.datas;
    },

    async getCustomerRiskAction() {
      const data = await getCustomerRiskAPI(this.currentCustomerId);
      this.riskInfo = data;
    },

    async getCustomerMeddicAction() {
      console.log("getCustomerMeddicAction: ", this.currentCustomerId);
      const data = await getCustomerMeddicAPI(this.currentCustomerId);
      this.meddicInfo = data;
      return data;
    },
    async updateCustomerMeddicAction(data) {
      data = {
        ...data,
        customerId: this.currentCustomerId
      };
      const res = await updateCustomerMeddicAPI(data);
      return res;
    },

    async getCustomerAttendeeAction(
      startTime,
      endTime = dayjs().format("YYYY-MM-DD")
    ) {
      this.customerStartTime = startTime;
      this.customerEndTime = endTime;

      const parameter = {
        startTime: formatCompletionTime(startTime, ParameterDateType.START_DATE),
        endTime: formatCompletionTime(endTime, ParameterDateType.ENE_DATE),
        myTeam: this.myTeam
      };
      const data = await customerAttendeeAPI(this.currentCustomerId, parameter);
      this.customerAttendeeList = data;

      let needReload = false;
      for (let i = 0; i < data.length; i++) {
        if (!data[i].requirementAnalysis) {
          needReload = true;
          break;
        }
      }
      if (needReload) {
        if (this.customerTimer) {
          clearTimeout(this.customerTimer);
        }
        this.customerTimer = setTimeout(
          () => {
            this.getCustomerAttendeeAction(
              this.customerStartTime,
              this.customerEndTime
            );
          },
          5000 + data.length * 1000
        );
      }
    },

    async remakeCustomerMeddicAction() {
      const data = await remakeCustomerMeddicAPI(this.currentCustomerId);
      this.getCustomerMeddicAction();
      return data;
    },

    async getCustomerTodoListAction(parameter) {
      parameter.myTeam = this.myTeam;
      // parameter.dptIds = [this.dptIds];
      parameter.pageSize = 500;
      const data = await getCustomerTodoListAPI(
        this.currentCustomerId,
        parameter
      );
      this.toDoList = data.datas;
    },

    async updateCustomerTodoStatusAction(confId, todoId, parameter) {
      const data = await updateCustomerTodoStatusAPI(confId, todoId, parameter);
      return data;
    },

    async getCompetitorsInfoAction(
      startTime,
      endTime = dayjs().format("YYYY-MM-DD")
    ) {
      const parameter = {
        startTime: formatCompletionTime(startTime, ParameterDateType.START_DATE),
        endTime: formatCompletionTime(endTime, ParameterDateType.ENE_DATE),
        myTeam: this.myTeam,
      };
      const customerId = this.currentCustomerId;
      const data = await getCustomerCompetitorsAPI(customerId, parameter);
      this.competitorsList = data;
      for (const element of data) {
        this.getCompetitorsDetailAction(customerId, element.id);
      }
      return data;
    },

    async getCompetitorsDetailAction(customerId, competitorId) {
      const data = await getCompetitorsDetailAPI(customerId, competitorId);
      this.competitorsInfo[competitorId] = data;
    },

    getDefaultDateRange() {
      console.log("getDefaultDateRange: ", this.filterStartTime);
      if (this.filterStartTime && this.filterEndTime) {
        return {
          st: this.filterStartTime,
          et: this.filterEndTime
        };
      }

      if (this.filterStartTime) {
        return {
          st: this.filterStartTime,
          et: dayjs().format("YYYY-MM-DD")
        };
      }
      return {
        st: getLongTimeAgo().startDate,
        et: dayjs().format("YYYY-MM-DD")
      };
    },

    async getOuterFiledPartnerAction() {
      let arr = await getOuterFiledPartnerAPI();
      this.outerFiledTemple = arr.filter(field => {
        return field.fieldStatus !== 0;
      });
    }
  }
});
